package com.newshub.admin.service.impl;

import com.newshub.admin.config.FetchSchedulerProperties;
import com.newshub.admin.entity.RssFeed;
import com.newshub.admin.mapper.RssFeedMapper;
import com.newshub.admin.service.AsyncFetchService;
import com.newshub.admin.service.FetchSchedulerService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 定时抓取调度服务实现
 */
@Slf4j
@Service
public class FetchSchedulerServiceImpl implements FetchSchedulerService {
    
    @Autowired
    private FetchSchedulerProperties properties;
    
    @Autowired
    private RssFeedMapper rssFeedMapper;
    
    @Autowired
    private AsyncFetchService asyncFetchService;
    
    @Override
    @BusinessLog(module = "定时抓取调度", description = "定时检查需要抓取的RSS源", level = LogLevel.INFO)
    @Scheduled(fixedRateString = "${fetch.scheduler.check-interval:60000}")
    public void checkScheduledTasks() {
        if (!properties.isEnabled()) {
            log.debug("定时调度器已禁用，跳过定时任务检查");
            return;
        }
        
        log.info("开始执行定时任务检查");
        
        try {
            // 1. 获取当前时间
            LocalTime now = LocalTime.now();
            String currentTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            
            // 2. 查询需要抓取的RSS源
            List<RssFeed> feedsToFetch = rssFeedMapper.findFeedsToFetch(currentTime);
            
            if (feedsToFetch.isEmpty()) {
                log.debug("当前时间 {} 没有需要抓取的RSS源", currentTime);
                return;
            }
            
            log.info("发现 {} 个RSS源需要抓取", feedsToFetch.size());
            
            // 3. 循环处理每个RSS源
            for (RssFeed feed : feedsToFetch) {
                try {
                    // 3.1 先标记今天已抓取（防止重复）
                    rssFeedMapper.updateLastFetchDate(feed.getId(), LocalDate.now());
                    
                    // 3.2 再提交到线程池执行（fetchCount和errorCount在任务完成后更新）
                    String taskId = asyncFetchService.executeFetchAsync(feed.getId().longValue());
                    
                    log.info("定时任务已提交，feedId: {}, feedName: {}, taskId: {}", 
                            feed.getId(), feed.getName(), taskId);
                    
                } catch (Exception e) {
                    log.error("提交定时抓取任务失败，feedId: {}, feedName: {} - {}", 
                            feed.getId(), feed.getName(), e.getMessage(), e);
                }
            }
            
            log.info("定时任务检查完成，共处理 {} 个RSS源", feedsToFetch.size());
            
        } catch (Exception e) {
            log.error("定时任务检查执行失败: {}", e.getMessage(), e);
        }
    }
    
    
    
    /**
     * 应用启动后初始化
     */
    @PostConstruct
    public void init() {
        if (properties.isEnabled()) {
            log.info("定时抓取调度器已启用，检查间隔: {}ms", properties.getCheckInterval());
        } else {
            log.info("定时抓取调度器已禁用");
        }
    }
}
